package com.yy.controller;

import com.yy.service.ex.*;
import com.yy.Utils.JsonResult;
import com.yy.Utils.JsonResult;
import com.yy.service.ex.*;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**
 * @author 鱼凫
 * @version 1.0
 * Create by 2021/10/29 23:50
 * @Description //TODO 控制层类的基类
 */


public class BaseController {
    public static final int OK = 200;

    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> result = new JsonResult<>(e);
        if (e instanceof UserNameDoplicatedException){
            result.setState(4000);
            result.setMessage("用户名已被占用");
        }else if (e instanceof InsertException){
            result.setState(5000);
            result.setMessage("添加用户失败，请联系系统管理员");
        }else if (e instanceof UserNotFoundException) {
            result.setState(5001);
            result.setMessage("用户数据不存在");
        } else if (e instanceof PasswordNotMatchException) {
            result.setState(5002);
            result.setMessage("用户名或密码错误");
        }else if (e instanceof UserRoleNotFoundException) {
            result.setState(5003);
            result.setMessage("该用户尚未分配角色");
        }
        else if (e instanceof  DeleteException){
            result.setState(5004);
            result.setMessage("删除数据时产生未知异常");
        }else if (e instanceof RoleNotFoundException){
            result.setState(5005);
            result.setMessage("角色数据不存在");
        }else if (e instanceof UpdateInfoException){
            result.setState(5006);
            result.setMessage("修改数据失败");
        }
        return result;
    }

    /**
     * 从HttpSession对象中获取uid
     * @param session HttpSession对象
     * @return 当前登录的用户的id
     */
    protected final String getUidFromSession(HttpSession session) {
        return String.valueOf(session.getAttribute("uid").toString());
    }

    /**
     * 从HttpSession对象中获取用户名
     * @param session HttpSession对象
     * @return 当前登录的用户名
     */
    protected final String getUsernameFromSession(HttpSession session) {
        return session.getAttribute("username").toString();
    }
}
